import { doLoginApi, getInfoApi } from '../../api/Denglu.js'
import { setToken, getToken, removeToken } from '../../cookies/index.js'
// import {resetRouter} from '../../router/index'
const state = {
    token: getToken(),
    roles: [],
    name: '',
    avatar: ''
}

const mutations = {
    SET_TOKEN(state, token) {
        state.token = token
    },
    SET_NAME(state, name) {
        state.name = name
    },
    SET_AVATAR(state, avatar) {
        state.avatar = avatar
    }
    , SET_ROLES(state, roles) {
        state.roles = roles
    }
}


const actions = {
    async doLogin({ commit }, form) {
        const { username, password } = form
        const { token } = await doLoginApi({ loginName: username, loginKey: password })
        setToken(token)
        commit("SET_TOKEN", token)
    },
    async getInfo({ commit }, token) {
        const { data } = await getInfoApi({ token })
        commit('SET_NAME', data.name)
        commit('SET_AVATAR', data.avatar)
        commit('SET_ROLES', data.roles)
        return data.roles
    },
    async doLogout({ commit }) {
        removeToken()
        commit("SET_TOKEN", '')
        commit('SET_ROLES', [])
    }


}


export default {
    namespaced: true,
    state,
    mutations,
    actions
}